package org.zjx.core.controller;

import org.zjx.core.DecisionTree;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

// 热更新决策树注册中心
public class HotSwapDecisionTreeRegistry extends DecisionTreeRegistry {
    private final Map<String, AtomicReference<DecisionTree>> versionedTrees = new ConcurrentHashMap<>();

    @Override
    public void register(String treeId, DecisionTree tree) {
        versionedTrees.computeIfAbsent(treeId, k -> new AtomicReference<>()).set(tree);
    }

    @Override
    public Optional<DecisionTree> get(String treeId) {
        return Optional.ofNullable(versionedTrees.get(treeId))
                .map(AtomicReference::get);
    }

    // 热更新方法
    public boolean hotUpdate(String treeId, DecisionTree newTree) {
        AtomicReference<DecisionTree> ref = versionedTrees.get(treeId);
        if (ref == null) return false;

        DecisionTree oldTree = ref.get();
        ref.set(newTree);
        return true;
    }
}